﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using ATW.MT.BUS;
using ATW.MT.CommonClass;
using BUS;
using System.Diagnostics.Contracts;
using System.Configuration;

namespace ATW.MT.SellManage
{
    public partial class ContractManage : CommonPage
    {
        bus_T_Contract TC = new bus_T_Contract();
        CommonHelp CH = new CommonHelp();
        Contact ct = new Contact();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["RequestID"] = null;
                BindData();
            }
        }
        private void BindData()
        {
            string name = txtName.Value.Trim();
            string type = ddlType.SelectedValue;
            string status = ddlStatus.SelectedValue;
            string timeFrom = txtPubStart.Value.Trim();
            string timeTo = txtPubEnd.Value.Trim();
            string title = txtTitle.Value.Trim();
            DateTime _timefrom = new DateTime();
            DateTime _timeend = new DateTime();
            try
            {
                if (name != "" && !common.filterChar(name)||title!=""&&!common.filterChar(title))
                {
                    Tips("查询条件中含有危险字符串！");
                    return;
                }
                if (timeFrom != "" && !DateTime.TryParseExact(timeFrom, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out _timefrom))
                {
                    Tips("起始时间格式错误！");
                    return;
                }
                if (timeTo != "" && !DateTime.TryParseExact(timeTo, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out _timeend))
                {
                    Tips("结束时间格式错误！");
                    return;
                }
                DataTable dt = TC.ContractPagerQuery(name, title,type, status, timeFrom, timeTo, AspNetPager1.CurrentPageIndex,
                    AspNetPager1.PageSize);
                if (dt != null && dt.Rows.Count > 0)
                {
                    AspNetPager1.RecordCount = Convert.ToInt32(dt.Rows[0]["TotalPagesize"]);
                }
                else
                {
                    AspNetPager1.RecordCount = 0;
                }
                rpList.DataSource = dt;
                rpList.DataBind();
            }
            catch (Exception ex)
            {

            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {//查询
            AspNetPager1.CurrentPageIndex = 1;
            BindData();
        }
        protected void AspNetPager1_pageChanged(object sender, EventArgs e)
        {//分页
            BindData();
        }
        protected void lbnContractDetail_Click(object sender, EventArgs e)
        {//详情
            LinkButton lbn = (LinkButton)sender;
            string ContractID = lbn.CommandArgument;
            string url = "../SellManage/ContractDetail.aspx?cid=" + ContractID + "&r=" + new Random().Next(1000).ToString();
            OpenDialog("合同详情", url, "width=1100,height=600");
        }
        protected void lbnAddEx_Click(object sender, EventArgs e)
        {//登记异常
            LinkButton lbn = (LinkButton)sender;
            string contractID = lbn.CommandArgument;
            string url = "../SellManage/_addExecption.aspx?cid=" + contractID + "&r=" + new Random().Next(1000);
            OpenDialog("登记异常", url, "width=400,height=300");
        }
        protected void lbnShowEx_Click(object sender, EventArgs e)
        {//查看异常
            LinkButton lbn = (LinkButton)sender;
            string contractID = lbn.CommandArgument;
            string url = "../SellManage/_exceptionList.aspx?cid=" + contractID + "&r=" + new Random().Next(1000);
            OpenDialog("查看异常", url, "width=500,height=400");
        }
        protected void lbnConfirm_Click(object sender, EventArgs e)
        {//执行合同
            try
            {
                LinkButton lbn = (LinkButton)sender;
                string OID = lbn.CommandArgument;
                HiddenField hdf = (HiddenField)lbn.Parent.FindControl("hdfType");
                if (hdf != null)
                {
                    string type = hdf.Value;
                    int result = 0;
                    if (type == "1")
                    {
                        result = TC.UpdateReqStatus(OID);
                    }
                    if (type == "2")
                    {
                        result = TC.UpdateResStatus(OID);
                    }
                    if (result > 0)
                    {
                        Tips("设置成功！");
                        BindData();
                    }
                    else
                    {
                        Tips("操作失败！");
                    }
                }
            }
            catch (Exception ex)
            {
                Tips(ex.Message);
            }
        }
        protected void lbnPush_Click(object sender, EventArgs e)
        {//生成供应商合同
            LinkButton lbn = (LinkButton)sender;
            string RequestID = lbn.CommandArgument;
            if (ViewState["RequestID"] != null && ViewState["RequestID"].ToString() == RequestID)
            {
                Tips("操作过于频繁，请稍后再试！");
                return;
            }
            try
            {
                //模板文件
                string modelPath = ConfigurationManager.AppSettings["SupContactFilePath"];
                //生成供应商合同
                string result = ct.GenerateSupplyContact(RequestID, modelPath);
                if (result == "1")
                {
                    //抓取要推送的合同列表
                    DataTable dt = TC.getPushList(RequestID);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string contractID = dt.Rows[i]["ContractID"].ToString();
                            string uid = dt.Rows[i]["tauloginid"].ToString();
                            //调用推送方法
                            pushContract(contractID, uid);
                        }
                        //修改客户合同状态
                        int r = TC.ContractPushed(RequestID);
                        Tips("合同已生成！");
                        BindData();
                        return;
                    }
                    else
                    {
                        Tips("未发现待生成的供应商合同，操作失败！");
                        return;
                    }
                }
                else
                {
                    Tips("合同生成失败！");
                    return;
                }
            }
            catch (Exception ex)
            {

            }
        }
        private void pushContract(string contractid, string uid)
        {//推送合同
            try
            {
                Dictionary<string, string> Parm = new Dictionary<string, string>();
                Parm.Add("ContractId", contractid);
                Parm.Add("Type", "2");
                T_Message Entry = new T_Message();
                Entry.tmType = "3";
                Entry.tmfrom = "system";
                Entry.tmTitle = "合同推送";
                Entry.tmto = uid;
                Entry.tmMessage = "尊敬的供应商你好，您的报价已生成合同，请确认";

                Entry.toType = "3";
                Entry.toId = contractid;

                CH.SendMessage(Entry, "3", Parm);
            }
            catch (Exception ex)
            {

            }
        }
        private void Tips(string s)
        {//提示
            StringBuilder strScript = new StringBuilder();
            strScript.Append(@"<script language=javascript>
                var divTips=new jSharp.popUpDiv('divMsg');
                document.getElementById('msgContent').innerHTML='" + s + @"';
                divTips.Show();
                var t=setTimeout(function(){
                    divTips.Close();
                    clearTimeout(t);
                },1000);
            </script>");
            this.ClientScript.RegisterStartupScript(this.GetType(), "tips", strScript.ToString());
        }
    }
}